#include "MLTools.h"
#include <time.h>

_MYLABLIB_BEGIN

CMLTools::CMLTools(void)
{
}

CMLTools::~CMLTools(void)
{
}

bool CMLTools::IsWhitespaceString(const std::wstring& wstr)
{
	int i;
	for(i=0; i<(int)wstr.length(); i++)
	{
		if (CMLTools::IsBlankChar(wstr[i]))
			continue;
		else
			return false;
	}
	return true;
}

bool CMLTools::SplitString(const std::wstring& wstrLine, std::vector<std::wstring>& vStrings,wchar_t delimiter/* = ' '*/)
{
	int i;
	int nLength = (int)wstrLine.length();
	wchar_t wch;
	std::wstring curStr;

	vStrings.clear();
	for (i=0; i<nLength; i++)
	{
		wch = wstrLine[i];
		if (CMLTools::IsBlankChar(wch) || wch == delimiter)
		{
			if (curStr.length() > 0)
			{
				vStrings.push_back(curStr);
				curStr.clear();
			}

			while (CMLTools::IsBlankChar(wch) || wch == delimiter)
			{
				i++;
				if (i == nLength)
					goto _BREAK_OUT;
				wch = wstrLine[i];
			}
			curStr += wch;
		}
		else
		{
			curStr += wch;
		}
	}

	if (curStr.length() > 0)
	{
		vStrings.push_back(curStr);
	}

_BREAK_OUT:
	return true;
}

bool CMLTools::SplitString(const std::wstring& wstrLine, std::vector<double>& vValues,wchar_t delimiter/* = ' '*/)
{
	int i;
	int nLength = (int)wstrLine.length();
	wchar_t wch;
	wchar_t curBuf[512];
	int curBufLen = 0;
	std::wstring curStr;

	vValues.clear();
	for (i=0; i<nLength; i++)
	{
		wch = wstrLine[i];
		if (CMLTools::IsBlankChar(wch) || wch == delimiter)
		{
			if (curBufLen > 0)
			{
				curBuf[curBufLen] = L'\0';
				vValues.push_back(_wtof(curBuf));
				curBufLen = 0;
			}

			while (CMLTools::IsBlankChar(wch) || wch == delimiter)
			{
				i++;
				if (i == nLength)
					goto _BREAK_OUT;
				wch = wstrLine[i];
			}
			curBuf[curBufLen++] = wch;
		}
		else
		{
			curBuf[curBufLen++] = wch;
		}
	}

	if (curBufLen > 0)
	{
		curBuf[curBufLen] = 0;
		vValues.push_back(_wtof(curBuf));
	}

_BREAK_OUT:
	return true;
}

bool CMLTools::GetNextToken(const std::wstring& wstrLine, std::wstring& wszToken)
{
	int i;
	int nLength = (int)wstrLine.length();
	wchar_t wch;
	wchar_t curBuf[512];
	int curBufLen = 0;

	i=0;
	wch = wstrLine[i];
	while (CMLTools::IsBlankChar(wch))
	{
		i++;
		if (i == nLength)
			return false; // No string left 
		wch = wstrLine[i];
	}

	while (CMLTools::IsBlankChar(wch) == false)
	{
		if (i == nLength)
			break;
		curBuf[curBufLen++] = wstrLine[i++];
		wch = wstrLine[i];
	}
	curBuf[curBufLen] = L'\0';
	wszToken = curBuf;

	return true;
}

long CMLTools::GetCurrentClock(void)
{
	return (long)clock();
}

double CMLTools::GetDurationInSecond(long lStartClock, long lFinishClock)
{
	return (double)((lFinishClock - lStartClock) / CLOCKS_PER_SEC);
}


_MYLABLIB_END

